<template>
  <div class="edit-container">
    <el-form v-loading="formLoading" ref="form" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="封面" prop="cover">
        <div style="display: flex;align-items: center;">
          <el-image v-if="form.cover" :src="imageUrl + form.cover" class="img" referrerpolicy="no-referrer"></el-image>
          <el-button type="primary" @click="uploads.show=true" size="mini">选择图片</el-button>
        </div>
      </el-form-item>
      <el-form-item label="活动名称" prop="activityName">
        <el-input v-model="form.activityName" placeholder="活动名称" maxlength="30" class="col"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="classification">
        <el-select v-model="form.classification" placeholder="请选择">
          <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="适用门店" prop="businessIdsArray">
        <el-select v-model="form.businessIdsArray" @change="businessData" multiple filterable
                   placeholder="请选择适用门店">
          <el-option
              v-for="item in businessList"
              :key="item.id"
              :label="item.businessName"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="倒计时" v-if="form.classification==1" prop="classification">
        <el-select v-model="form.timeName" @change="changeTime" placeholder="请选择">
          <el-option
              v-for="item in timeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
        <span style="margin-left: 20px">倒计时截止: {{ form.endTime }}</span>
      </el-form-item>
      <el-row :gutter="10" align="middle">
        <el-col :span="10">
          <el-form-item label="现价" prop="price">
            <el-input-number placeholder="现价" v-model="form.price" class="col" maxlength="5"
                             style="width: 200px" :precision="2" :min="0" :max="99999"/>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="原价" prop="originalPrice">
            <el-input-number placeholder="原价" v-model="form.originalPrice" class="col" maxlength="5"
                             style="width: 200px" :precision="2" :min="0" :max="99999"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="库存" prop="number">
        <el-input type="number" placeholder="库存" v-model="form.number" class="col" maxlength="2000"/>
      </el-form-item>
      <el-form-item label="优惠折扣" prop="preferential">
        <el-input-number v-model="form.preferential" placeholder="优惠折扣" maxlength="4"
                         class="col" :precision="2" :min="0" :max="10"></el-input-number>
      </el-form-item>

      <el-form-item label="消费须知" prop="consumeNotice">
        <el-select v-model="form.consumeNotice" placeholder="请选择">
          <el-option label="周一至周五可用" value="周一至周五可用"></el-option>
          <el-option label="周一至周天可用" value="周一至周天可用"></el-option>
          <el-option label="周内任意时间可用" value="周内任意时间可用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务保障" prop="serviceGuarantee">

        <el-select v-model="form.serviceGuarantee" placeholder="请选择">
          <el-option label="免预约 随时退 过期自动退" value="免预约 随时退 过期自动退"></el-option>
          <el-option label="随时退 过期自动退" value="随时退 过期自动退"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="有效期限" prop="validPeriod">
        <el-date-picker
            v-model="value1"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="使用规则" prop="consumeNoticeDetails">
        <el-select v-model="form.consumeNoticeDetails" placeholder="请选择模板">
          <el-option label="模板 1" value="1.不可使用包间
2.本单发票由商家提供，详情请咨询商家
3.堂食外带均可
4.团购用户不可同时享受商家其他优惠
5.使用优惠券购买团单，有效期以优惠券规则为准佳
6.无需预约，消费高峰期可能需要等位"></el-option>
          <el-option label="模板 2" value="1.本单发票由商家提供，详情请咨询商家
2.仅限堂食
3.不可使用包间和雅座使用
4.团购用户不可同时享受商家其他优惠
5.使用优惠券购买团单，有效期以优惠券规则为准
6.无需预约，消费高峰期可能需要等位"></el-option>
        </el-select>
        <el-input style="margin-top: 5px" type="textarea" :rows="5" v-model="form.consumeNoticeDetails"
                  placeholder="使用规则" maxlength="500" class="col"/>
      </el-form-item>
      <el-form-item label="团购详情" prop="groupBuyingDetails">
        <el-input type="textarea" :rows="5" v-model="form.groupBuyingDetails" placeholder="团购详情" maxlength="500"
                  class="col"></el-input>
      </el-form-item>
      <el-form-item label="团购分类" prop="groupBuyingId">
        <el-select v-model="groupBuyingArray" filterable multiple placeholder="请选择" style="width: 520px">
          <el-option
              v-for="item in classificationList"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否为甄选活动" prop="isPick">
        <el-select v-model="form.isPick" placeholder="请选择">
          <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary"
                   @click="handlerSubmit" v-has-permi="['admin:merchantActivities:save']">保存
        </el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
        :visible.sync="uploads.show"
        title="上传封面"
        :append-to-body="true"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px">
      <UploadFile
          v-if="uploads.show"
          :multiple="uploads.multiple"
          :module-id="5"
          :business-id="businessId"
          @getFile="getFile"
          ref="uploads"
      />
    </el-dialog>
  </div>
</template>
<script>
import {detail, getClassificationDrop, getClassificationList, save} from "@/api/merchantActivity";
import {getForm} from "@/utils/utils";
import UploadFile from "@/components/File/UploadFile.vue";
import {list} from "@/api/business";

export default {
  components: {UploadFile},
  props: {
    id: {
      default: null
    },
    businessId: {
      default: null
    }
  },
  data() {
    return {
      value1: '',
      selectedTemplate: '',
      editedTemplate: '',
      form: {
        id: null,
        activityName: '',
        price: 0,
        originalPrice: 0,
        groupBuyingId: '',
        preferential: '',
        number: '',
        consumeNotice: '',
        serviceGuarantee: '',
        validPeriod: '',
        consumeNoticeDetails: '',
        isPick: '',
        businessId: '',
        cover: '',
        groupBuyingDetails: '',
        classification: '',
        endTime: '',
        timeName: '',
        businessIds: '',
        businessIdsArray: [] // 保存选中项的数组
      },
      groupBuyingArray: [],
      businessList: [],
      rules: {
        cover: [{required: true, message: '请选择封面', trigger: ['blur']}],
        activityName: [{required: true, message: '请填写活动名称', trigger: ['blur']}],
        classification: [{required: true, message: '请选择活动类型', trigger: ['blur']}],
        price: [{required: true, message: '请填写现价', trigger: ['blur']}],
        originalPrice: [{required: true, message: '请填写原价', trigger: ['blur']}],
        preferential: [{required: true, message: '请填写优惠折扣', trigger: ['blur']}],
        consumeNotice: [{required: true, message: '请填写消费须知', trigger: ['blur']}],
        serviceGuarantee: [{required: true, message: '请填写服务保障', trigger: ['blur']}],
        validPeriod: [{required: true, message: '请填写有效期限', trigger: ['blur']}],
        consumeNoticeDetails: [{required: true, message: '请填写消费须知详情', trigger: ['blur']}],
        isPick: [{required: true, message: '请选择是否为甄选活动', trigger: ['blur']}],
        groupBuyingDetails: [{required: true, message: '请填写团购详情', trigger: ['blur']}],
        groupBuyingArray: [{required: true, message: '请选择团购分类', trigger: ['blur']}],
        number: [{required: true, message: '请填写库存', trigger: ['blur']}],
      },
      roles: [],
      classificationList: [],
      saveLoading: false,
      formLoading: false,
      uploads: {
        show: false,
        multiple: false,
      },
      typeList: [{id: 1, name: "是"}, {id: 2, name: "否"},],
      classList: [{id: 1, name: '免费'}, {id: 5, name: '消费多少送多少'}],
      timeList: [
        {id: 1, name: '24小时倒计时', value: 24},
        {id: 2, name: '48小时倒计时', value: 48},
        {id: 3, name: '72小时倒计时', value: 72}
      ],
      imageUrl: '',
    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL
    this.getBusinessList()
    this.getClassification()
    if (this.id) {
      this.getDetail();
    }
  },
  watch: {
    selectedTemplate(value) {
      this.editedTemplate = value;
    },
  },

  methods: {
    getClassification() {
      getClassificationDrop(this.businessId).then(res => {
        this.classificationList = res;
      }).finally(() => {
      })
    },
    businessData(e) {
      console.log(e)
    },
    getBusinessList() {
      list({page: 1, limit: 5000}).then(res => {
        this.businessList = res.list
      })
    },
    changeTime(e) {
      // 获取传入的id
      const id = e;
      // 在timeList中查找对应的项
      const selectedItem = this.timeList.find(item => item.id === id);
      // 如果找到了对应的项，获取其value
      if (selectedItem) {
        // const value = selectedItem.value;
        // // 计算新的结束时间
        // const now = new Date();
        // now.setHours(now.getHours() + value);
        // // 将新的结束时间格式化为字符串
        // this.form.endTime = this.formatDate(now);
        const date = new Date();
        let str = '';
        let y = date.getFullYear().toString();
        let m = (date.getMonth() + 1).toString();
        m = m.length == 1 ? '0' + m : m
        let d = date.getDate().toString();
        d = d.length == 1 ? '0' + d : d
        let h = '00'
        let i = '00'
        let s = '00'
        str = y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s
        this.form.endTime = str;
        console.log(this.form.endTime)
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getDetail() {
      this.formLoading = true
      detail(this.id).then(res => {
        getForm(res, this.form);
        if (this.form.businessIds) {
          this.form.businessIdsArray = this.form.businessIds.split(',').map(id => parseInt(id));
        }
        if (this.form.groupBuyingId) {
          this.groupBuyingArray = this.form.groupBuyingId.split(",").map(Number);
        }
      }).finally(() => {
        this.formLoading = false;
      })
    },
    getFile(fileList) {
      this.form.cover = fileList[0].url
      this.uploads.show = false
    },
    handleDateChange(value) {
      this.form.validPeriod = value[0] + '至' + value[1];
    },
    handlerSubmit() {
      this.form.businessIds = this.form.businessIdsArray.join(',');
      if (this.saveLoading || this.formLoading) {
        return;
      }
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        this.form.groupBuyingId = this.groupBuyingArray.join(',');
        this.form.businessId = this.businessId;
        save(this.form).then(() => {
          this.$message.success('保存成功');
          this.close();
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    close() {
      this.$emit('hideEditDialog')
    }
  }
}
</script>
<style lang="scss" scoped>

.col {
  width: 520px;
}

.img {
  width: 120px;
  height: 120px;
  margin-right: 10px;
}
</style>
